﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace LS.Screening.UI.Common
{
    public static class ServiceHelper
    {
        private static IServiceProvider serviceProvider;
        private static IServiceCollection services;

        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="actions"></param>
        public static void RegisterServices(List<Type> typeList)
        {
            if (services == null)
                services = new ServiceCollection();
            foreach (var type in typeList)
            {
                services.AddSingleton(type);
            }
        }

        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="actionList"></param>
        public static void RegisterServices(params Assembly[] assemblies)
        {
            if (services == null)
                services = new ServiceCollection();
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes().Where(p => !p.IsAbstract && !p.IsInterface && p.FullName.EndsWith("ViewModel"));
                foreach (var type in types)
                {
                    services.AddSingleton(type);
                }
            }
        }

        /// <summary>
        /// 构建服务
        /// </summary>
        public static void BuildServices()
        {
            if (services == null)
            {
                throw new Exception("服务为注册，请先调用RegisterServices方法");
            }
            serviceProvider = services.BuildServiceProvider();
        }

        /// <summary>
        /// 获得服务实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return serviceProvider.GetRequiredService<T>();
        }
    }
}
